package com.zzl.myblog.View.Activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.zzl.myblog.Bean.ViewBean.blog;
import com.zzl.myblog.R;
import com.zzl.myblog.Utils.SqliteUtils;

import java.util.List;

public class editBlog extends AppCompatActivity implements View.OnClickListener {
    Boolean isSaved=false;
    EditText GitHub,CSDN,Gitee;
    Button saveBtn;
    String msg;

    String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_blog);
        Intent intent = getIntent();
        username = intent.getStringExtra("username");

        initView();
        initData();
    }
    private void initView(){
        GitHub = findViewById(R.id.GitHub);
        Gitee = findViewById(R.id.Gitee);
        CSDN = findViewById(R.id.CSDN);
        saveBtn = findViewById(R.id.save);

        saveBtn.setOnClickListener(this);
    }

    /*
    从sqlite中读取对应用户的数据
     */
    private void initData() {
        List<blog> blogList = SqliteUtils.queryUser(username);
        if (blogList.size()!=0){
            isSaved = true;
            blog blog = blogList.get(0);
            if(blog.getGiteeURL().contains("http")){
                Gitee.setText(blog.getGiteeURL());
            }
            if(blog.getCSDNURL().contains("http")){
                CSDN.setText(blog.getCSDNURL());
            }
            if(blog.getGitHubURL().contains("http")){
                GitHub.setText(blog.getGitHubURL());
            }
        }
    }

    /*
    更改sqllite中所有博客数据
     */
    @Override
    public void onClick(View v) {
        String GitHub_URL = GitHub.getText().toString();
        String CSDN_URL = CSDN.getText().toString();
        String Gitee_URL = Gitee.getText().toString();

        blog blog = new blog();
        blog.setCSDNURL(CSDN_URL);
        blog.setGiteeURL(Gitee_URL);
        blog.setGitHubURL(GitHub_URL);
        blog.setUsername(username);

        if(isSaved){ // 已经存储了,只需更新表项即可
            msg = SqliteUtils.updateBlogURL(blog);
        }else{ // 未存储过
            msg = SqliteUtils.saveBlogURL(blog);
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}